from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.core.paginator import Paginator
from django.utils import timezone
from django.db import models
from .models import Notification
from .forms import NotificationForm

def is_admin(user):
    """检查用户是否是管理员"""
    return user.is_staff or (hasattr(user, 'profile') and user.profile.role == 'admin')

@login_required
@user_passes_test(is_admin)
def notification_list(request):
    """通知列表 - 管理员视图"""
    # 搜索和筛选功能
    search_query = request.GET.get('search', '')
    status_filter = request.GET.get('status', '')
    
    notifications = Notification.objects.all().select_related('created_by')
    
    # 搜索过滤
    if search_query:
        notifications = notifications.filter(
            models.Q(title__icontains=search_query) |
            models.Q(content__icontains=search_query)
        )
    
    # 状态过滤
    if status_filter == 'active':
        notifications = notifications.filter(is_active=True)
    elif status_filter == 'inactive':
        notifications = notifications.filter(is_active=False)
    elif status_filter == 'current':
        now = timezone.now()
        notifications = notifications.filter(
            is_active=True,
            start_date__lte=now,
            end_date__gte=now
        )
    elif status_filter == 'expired':
        now = timezone.now()
        notifications = notifications.filter(end_date__lt=now)
    
    # 分页
    paginator = Paginator(notifications.order_by('-created_at'), 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'notifications': page_obj,
        'search_query': search_query,
        'status_filter': status_filter,
        'now': timezone.now(),
    }
    return render(request, 'notifications/list.html', context)

@login_required
@user_passes_test(is_admin)
def notification_create(request):
    """创建通知"""
    if request.method == 'POST':
        form = NotificationForm(request.POST)
        if form.is_valid():
            notification = form.save(commit=False)
            notification.created_by = request.user
            notification.save()
            messages.success(request, '通知创建成功！')
            return redirect('notifications:notification_list')
        else:
            messages.error(request, '请修正以下错误：')
    else:
        form = NotificationForm()
    
    return render(request, 'notifications/form.html', {
        'form': form,
        'title': '创建通知'
    })

@login_required
@user_passes_test(is_admin)
def notification_edit(request, pk):
    """编辑通知"""
    notification = get_object_or_404(Notification, pk=pk)
    
    if request.method == 'POST':
        form = NotificationForm(request.POST, instance=notification)
        if form.is_valid():
            form.save()
            messages.success(request, '通知更新成功！')
            return redirect('notifications:notification_list')
        else:
            messages.error(request, '请修正以下错误：')
    else:
        form = NotificationForm(instance=notification)
    
    return render(request, 'notifications/form.html', {
        'form': form,
        'title': '编辑通知',
        'notification': notification
    })

@login_required
@user_passes_test(is_admin)
def notification_delete(request, pk):
    """删除通知"""
    notification = get_object_or_404(Notification, pk=pk)
    
    if request.method == 'POST':
        notification.delete()
        messages.success(request, '通知删除成功！')
        return redirect('notifications:notification_list')
    
    return render(request, 'notifications/confirm_delete.html', {
        'notification': notification
    })

@login_required
@user_passes_test(is_admin)
def notification_toggle(request, pk):
    """切换通知激活状态"""
    notification = get_object_or_404(Notification, pk=pk)
    
    if request.method == 'POST':
        notification.is_active = not notification.is_active
        notification.save()
        
        status = "激活" if notification.is_active else "停用"
        messages.success(request, f'通知已{status}！')
    
    return redirect('notifications:notification_list')

def get_user_notifications(user):
    """获取用户相关的有效通知"""
    if not user.is_authenticated:
        return []
    
    now = timezone.now()
    
    # 获取用户角色
    user_role = 'customer'  # 默认角色
    if hasattr(user, 'profile'):
        user_role = user.profile.role
    
    # 查询有效的通知：激活状态且在有效期内，且目标角色包含用户角色或'all'
    notifications = Notification.objects.filter(
        is_active=True,
        start_date__lte=now,
        end_date__gte=now
    ).filter(
        models.Q(target_roles__contains=user_role) |
        models.Q(target_roles__contains='all')
    ).order_by('-priority', '-created_at')
    
    return notifications
